package cn.view;

import cn.comon.CSVUtil;
import cn.comon.VerticalTextCellRenderer;
import cn.dao.GoodsDao;
import cn.entity.Goods;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class GoodsSQView extends JInternalFrame {
    JTable detail;
    DefaultTableModel model;
    JPanel Jbutton;

    public GoodsSQView() {
        super("商品统计查询页面", false, true, false, true);
        initializeComponents();
        this.setSize(700, 500);
        this.setVisible(true); // 确保窗口显示
    }

    private void initializeComponents() {
        getContentPane().setLayout(new BorderLayout());
        getDetailData();
        setButton();
    }

    private void getDetailData() {
        GoodsDao dao = new GoodsDao();
        List<Object[]> ls = dao.selectAll();
        String[] title = {"商品编号", "商品名称", "商品单价", "客户编号", "商品简介", "备注"};
        model = new DefaultTableModel(ls.toArray(new Object[][]{}), title);
        detail = new JTable(model);
        detail.setDefaultEditor(Object.class, null);
        detail.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        setColumnWidths(detail, new int[]{100, 100, 80, 100, 140, 140});
        detail.setRowHeight(15);
        for (int i = 0; i < detail.getColumnCount(); i++) {
            detail.getColumnModel().getColumn(i).setCellRenderer(new VerticalTextCellRenderer());
        }

        JScrollPane scrollPane = new JScrollPane(detail, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    private void setColumnWidths(JTable table, int[] widths) {
        for (int i = 0; i < widths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        }
    }

    public void refreshGoodsData() {
        GoodsDao dao = new GoodsDao();
        List<Object[]> ls = dao.selectAll();
        model.setRowCount(0);
        for (Object[] row : ls) {
            model.addRow(row);
        }
    }

    private void showQueryGoodsDialog() {
        JTextField[] fields = new JTextField[6];
        JPanel panel = createGoodsFormPanel(fields);

        int result = JOptionPane.showConfirmDialog(null, panel, "查询商品", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            Goods criteria = getGoodsFromFields(fields);

            GoodsDao dao = new GoodsDao();
            List<Goods> goodsList = dao.queryGoods(criteria);

            if (goodsList.isEmpty()) {
                JOptionPane.showMessageDialog(null, "没有符合的商品信息");
            } else {
                model.setRowCount(0);
                for (Goods good : goodsList) {
                    model.addRow(new Object[]{
                            good.getGid(),
                            good.getGname(),
                            good.getPrice(),
                            good.getCid(),
                            good.getIntroduction(),
                            good.getNotes()
                    });
                }
            }
        }
    }

    private JPanel createGoodsFormPanel(JTextField[] fields) {
        JPanel panel = new JPanel(new GridLayout(6, 2));
        String[] labels = {"商品编号", "商品名称", "商品单价", "客户编号", "商品简介", "备注"};
        for (int i = 0; i < fields.length; i++) {
            panel.add(new JLabel(labels[i]));
            fields[i] = new JTextField();
            panel.add(fields[i]);
        }
        return panel;
    }

    private Goods getGoodsFromFields(JTextField[] fields) {
        Goods good = new Goods();
        good.setGid(fields[0].getText()); // 商品编号
        good.setGname(fields[1].getText()); // 商品名称

        String priceText = fields[2].getText().trim();
        if (!priceText.isEmpty()) {
            good.setPrice(Float.parseFloat(priceText)); // 商品单价，注意转换为Float类型
        }
        good.setCid(fields[3].getText()); // 客户编号
        good.setIntroduction(fields[4].getText()); // 商品简介
        good.setNotes(fields[5].getText()); // 备注
        return good;
    }

    private void showStockStatistics() {
        GoodsDao dao = new GoodsDao();
        List<Object[]> stockData = dao.getStockStatistics();
        String[] title = {"商品编号", "商品名称", "商品单价", "客户编号", "库存数量"};
        model.setDataVector(stockData.toArray(new Object[][]{}), title);

        int totalStock = stockData.stream().mapToInt(row -> (Integer) row[4]).sum();
        int totalTypes = stockData.size();
        JOptionPane.showMessageDialog(null, "当前商品库存总数量：" + totalStock + "，共计" + totalTypes + "种商品。");
    }

    private void showPayStatistics() {
        GoodsDao dao = new GoodsDao();
        List<Object[]> purchaseData = dao.getPurchaseStatistics();
        String[] title = {"商品编号", "商品名称", "商品单价", "客户编号", "采购数量", "采购金额"};
        model.setDataVector(purchaseData.toArray(new Object[][]{}), title);
    }

    private void exportCurrentTableToCSV() {
        int rowCount = model.getRowCount();
        int columnCount = model.getColumnCount();
        List<Object[]> data = new ArrayList<>();
        for (int i = 0; i < rowCount; i++) {
            Object[] row = new Object[columnCount];
            for (int j = 0; j < columnCount; j++) {
                row[j] = model.getValueAt(i, j);
            }
            data.add(row);
        }

        String[] headers = new String[columnCount];
        for (int i = 0; i < columnCount; i++) {
            headers[i] = model.getColumnName(i);
        }

        File csvFile = CSVUtil.createCSVFile(headers, data, "output/path", "商品数据");
        if (csvFile != null) {
            JOptionPane.showMessageDialog(null, "商品数据已成功导出到: " + csvFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(null, "导出商品数据失败");
        }
    }

    private void setButton() {
        Jbutton = new JPanel();
        Jbutton.setLayout(new FlowLayout());

        JButton queryButton = new JButton("查询商品");
        queryButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showQueryGoodsDialog();
            }
        });

        JButton stockButton = new JButton("库存统计");
        stockButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showStockStatistics();
            }
        });

        JButton payButton = new JButton("采购统计");
        payButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showPayStatistics();
            }
        });

        JButton exportButton = new JButton("导出CSV");
        exportButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                exportCurrentTableToCSV();
            }
        });

        Jbutton.add(queryButton);
        Jbutton.add(stockButton);
        Jbutton.add(payButton);
        Jbutton.add(exportButton);

        getContentPane().add(Jbutton, BorderLayout.SOUTH);
    }
}
